Thu , Nov 23 2023
A copy constructor in C# is a constructor used to create a new object as a copy of an existing object. It enables the duplication of an object’s properties while keeping the original and new objects independent. This is particularly useful when you want to create a separate instance without referencing the original object, avoiding unintended changes to the original object’s state.
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
// Example of how a copy constructor works
Employee objEmp = new()
{
EmpId = 1,
FirstName = "lal ju"
};
Console.WriteLine("Original Object (objEmp):");
Console.WriteLine($"EmpId: {objEmp.EmpId}, FirstName: {objEmp.FirstName}");
// Creating a new object using the copy constructor
Employee objEmp2 = new Employee(objEmp);
Console.WriteLine("Copied Object (objEmp2):");
Console.WriteLine($"EmpId: {objEmp2.EmpId}, FirstName: {objEmp2.FirstName}");
// Modifying the original object
objEmp.EmpId = 2;
objEmp.FirstName = "ladli ju";
Console.WriteLine("Modified Original Object (objEmp):");
Console.WriteLine($"EmpId: {objEmp.EmpId}, FirstName: {objEmp.FirstName}");
Console.WriteLine("Copied Object Remains Unchanged (objEmp2):");
Console.WriteLine($"EmpId: {objEmp2.EmpId}, FirstName: {objEmp2.FirstName}");
}
}
public class Employee
{
public int EmpId { get; set; }
public string FirstName { get; set; }
// Default constructor
public Employee()
{
}
// Copy constructor
public Employee(Employee objEmp)
{
this.EmpId = objEmp.EmpId;
this.FirstName = objEmp.FirstName;
}
}
Employee class contains a parameterless default constructor to initialize new objects.Employee(Employee objEmp) accepts an existing Employee object as a parameter and assigns its properties (EmpId and FirstName) to the new object.Main method, the objEmp object is initialized and printed. A new object objEmp2 is created using the copy constructor, duplicating objEmp’s properties at the time of creation.objEmp object’s properties (e.g., EmpId and FirstName) do not affect objEmp2, demonstrating the independence of the two objects.Copy constructors are ideal when working with complex objects where simple assignment may lead to shared references, causing unexpected changes in the original object.
I am an engineer with over 10 years of experience, passionate about using my knowledge and skills to make a difference in the world. By writing on LifeDB, I aim to share my thoughts, ideas, and insights to inspire positive change and contribute to society. I believe that even small ideas can create big impacts, and I am committed to giving back to the community in every way I can.
Leave a Reply